var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var cors = require("cors");
var session = require('express-session');

var logger = require('./utils/logger');
var restful = require('./utils/restful');

var indexRouter = require('./routes/index');

var app = express();
app.disable('x-powered-by');

// view engine setup

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(express.static(path.join(__dirname, '../front_end')));

// middlewares
app.use(cors());

app.use(session({
  secret: process.env.SESSION_SECRETKEY,
  resave: true, // 每次请求都重新设置session cookie的过期时间
  saveUninitialized: true,
  cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 7 // 一周
  }
}));

app.use(logger(':method (:status_color) :url \[:res[content-length]\] :response-time ms'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(restful);

// routes
app.use('/api', indexRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
